package com.mall.util.distributed.raft.rpc;

import com.alipay.remoting.exception.RemotingException;
import com.alipay.remoting.rpc.RpcClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class DefaultRaftClient implements RaftClient {
    private final RpcClient rpcClient;

    @Override
    public Response send(Request request, int timeout) {
        Response response = null;
        try {
            response = (Response) rpcClient.invokeSync(request.getUrl(), request, timeout);
        } catch (RemotingException e) {
            if(log.isErrorEnabled()) {
                log.error("Remote call failed during sending", e.getCause());
            }
            throw new RuntimeException();
        } catch (InterruptedException e) {
            if(log.isErrorEnabled()) {
                log.error("The remote call was interrupted during sending", e.getCause());
            }
            throw new RuntimeException();
        }
        return response;
    }
}
